package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLocationService implements com.itheima.service.mongo.UserLocationService {
   @Autowired
   private MongoTemplate mongoTemplate;
    @Override
    public void saveUserLocation(Double longitude, Double latitude, String addrStr, Long userId) {
        // 1.先查
        UserLocation userLocation = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), UserLocation.class);
        if (userLocation==null) {
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            userLocation.setLastUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);

        }else {
            userLocation.setAddress(addrStr);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setLastUpdated(userLocation.getUpdated());
            userLocation.setUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }

    }
    //搜附近
    @Override
    public List<Long> searchNearUser(Long userId, Long distance) {
        //找圆心
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);
        GeoJsonPoint geoJsonPoint = userLocation.getLocation();
        // 2.指定半径范围
        Distance dis = new Distance(distance/1000, Metrics.KILOMETERS);
        //画圆
        Circle circle = new Circle(geoJsonPoint,dis);
        // 在园内查找
        Query query = new Query(Criteria.where("location").withinSphere(circle));
        List<? extends UserLocation> userLocations = mongoTemplate.find(query, userLocation.getClass());
        ArrayList<Long>  nearUserIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userLocations)) {
            for (UserLocation location : userLocations) {
                Long userId1 = location.getUserId();
                nearUserIdList.add(userId1);
            }

        }

        return nearUserIdList;
    }
}
